package com.github.bdeenyy.asv2.controller;

import com.github.bdeenyy.asv2.Main;
import com.github.bdeenyy.asv2.model.VectorData;
import com.github.bdeenyy.asv2.service.VectorCalculator;
import com.github.bdeenyy.asv2.ui.VectorDrawer;
import com.github.bdeenyy.asv2.util.ClipboardHandler;
import com.github.bdeenyy.asv2.util.ExcelLoader;
import javafx.beans.property.DoubleProperty;
import javafx.beans.property.SimpleDoubleProperty;
import javafx.collections.FXCollections;
import javafx.collections.ObservableList;
import javafx.geometry.Insets;
import javafx.scene.control.*;
import javafx.scene.control.cell.TextFieldTableCell;
import javafx.scene.layout.*;
import javafx.scene.paint.Color;
import javafx.util.converter.NumberStringConverter;
import org.controlsfx.control.textfield.TextFields;

import java.util.List;

public class DataTabController {
    // Константа для максимальной длины результирующего вектора
    private static final double MAX_RESULTANT_LENGTH = 66; // например, 200 пикселей

    private TableView<VectorData> table;
    private final DoubleProperty azimuth = new SimpleDoubleProperty(0);
    private RadioButton clockwiseButton;
    private final ExcelLoader excelLoader;
    private final ClipboardHandler clipboardHandler;
    private final ResultTabController resultTabController;

    public DataTabController(ResultTabController resultTabController) {
        this.excelLoader = new ExcelLoader();
        this.clipboardHandler = new ClipboardHandler();
        this.resultTabController = resultTabController;
    }

    public Tab createDataTab() {
        Tab tab = new Tab("Данные");
        tab.setClosable(true);
        tab.setOnClosed(_ -> Main.setDataTabClosed(true));

        table = new TableView<>();
        table.setEditable(true);

        TableColumn<VectorData, String> nameColumn = new TableColumn<>("Сечение");
        nameColumn.setCellValueFactory(cellData -> cellData.getValue().nameProperty());
        nameColumn.setCellFactory(TextFieldTableCell.forTableColumn());
        nameColumn.setMinWidth(100);

        TableColumn<VectorData, String> length1Column = new TableColumn<>("ОП1");
        length1Column.setCellValueFactory(cellData -> cellData.getValue().length1Property());
        length1Column.setCellFactory(TextFieldTableCell.forTableColumn());
        length1Column.setMinWidth(100);

        TableColumn<VectorData, String> length2Column = new TableColumn<>("ОП2");
        length2Column.setCellValueFactory(cellData -> cellData.getValue().length2Property());
        length2Column.setCellFactory(TextFieldTableCell.forTableColumn());
        length2Column.setMinWidth(100);

        TableColumn<VectorData, String> length3Column = new TableColumn<>("ОП3");
        length3Column.setCellValueFactory(cellData -> cellData.getValue().length3Property());
        length3Column.setCellFactory(TextFieldTableCell.forTableColumn());
        length3Column.setMinWidth(100);


        table.getColumns().addAll(nameColumn, length1Column, length2Column, length3Column);
        table.setItems(getInitialData());

        Button calculateButton = new Button("Рассчитать");
        Button pasteButton = new Button("Вставить из буфера");
        Button addButton = new Button("Добавить строку");
        Button deleteButton = new Button("Удалить строку");
        Button loadButton = new Button("Загрузить Excel");

        TextField azimuthField = TextFields.createClearableTextField();
        azimuthField.textProperty().bindBidirectional(azimuth, new NumberStringConverter());
        azimuthField.setText("0");

        Label azimuthLabel = new Label("Азимут:");

        ToggleGroup directionGroup = new ToggleGroup();
        RadioButton counterClockwiseButton = new RadioButton("Против часовой");
        counterClockwiseButton.setToggleGroup(directionGroup);
        counterClockwiseButton.setSelected(true);
        clockwiseButton = new RadioButton("По часовой");
        clockwiseButton.setToggleGroup(directionGroup);

        VBox controlsBox = new VBox(10, azimuthLabel, azimuthField, counterClockwiseButton, clockwiseButton, calculateButton, pasteButton, addButton, deleteButton, loadButton);
        controlsBox.setPadding(new Insets(10));

        HBox dataContent = new HBox(10, table, controlsBox);
        dataContent.setPadding(new Insets(10));
        tab.setContent(dataContent);

        calculateButton.setOnAction(_ -> drawResultantVectors());

        pasteButton.setOnAction(_ -> {
            ObservableList<VectorData> dataFromClipboard = clipboardHandler.pasteFromClipboard();
            table.getItems().addAll(dataFromClipboard);
        });

        addButton.setOnAction(_ -> table.getItems().add(new VectorData("", "", "", "")));

        deleteButton.setOnAction(_ -> {
            VectorData selectedItem = table.getSelectionModel().getSelectedItem();
            if (selectedItem != null) {
                table.getItems().remove(selectedItem);
            }
        });

        loadButton.setOnAction(_ -> {
            ObservableList<VectorData> dataFromFile = excelLoader.loadFromExcel();
            table.setItems(dataFromFile);
        });

        return tab;
    }

    private ObservableList<VectorData> getInitialData() {
        return FXCollections.observableArrayList(
                new VectorData("10", "10", "20", "-30"),
                new VectorData("20", "10", "-20", "30"));
    }

    private void drawResultantVectors() {
        resultTabController.clearDrawingGridPane();

        int column = 0;
        int row = 0;
        int maxColumns = 3;

        boolean isClockwise = clockwiseButton.isSelected();

        List<VectorData> vectorDataList = table.getItems();

        for (VectorData data : vectorDataList) {
            try {
                String name = data.getName();
                double length1 = Double.parseDouble(data.getLength1());
                double length2 = Double.parseDouble(data.getLength2());
                double length3 = Double.parseDouble(data.getLength3());

                double[] vectorLengths = {length1, length2, length3};
                double[][] vectors = VectorCalculator.calculateVectors(vectorLengths, isClockwise);

                double[] resultVector = VectorCalculator.calculateResultantVector(vectors);
                double resultLength = Math.sqrt(resultVector[0] * resultVector[0] + resultVector[1] * resultVector[1]);

                // Вычисление масштаба для результирующего вектора
                double scale = calculateScale(resultLength);

                Pane drawingPane = new Pane();
                drawingPane.setPrefSize(300, 250);
                drawingPane.setBackground(new Background(new BackgroundFill(Color.WHITE, CornerRadii.EMPTY, Insets.EMPTY)));

                VectorDrawer.drawTriangleAndVector(drawingPane, 100, 100, 150, resultVector, name, resultLength, azimuth.get(), scale, isClockwise);

                resultTabController.addDrawingPane(drawingPane, column, row);

                column++;
                if (column == maxColumns) {
                    column = 0;
                    row++;
                }

            } catch (NumberFormatException e) {
                System.out.println("Please enter valid numbers for vector lengths and scale.");
            }
        }
    }

    // Метод для вычисления масштабного коэффициента
    private double calculateScale(double resultLength) {
        return MAX_RESULTANT_LENGTH / resultLength;
    }
}
